package com.bohan.main;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class WriterJason {
	public WriterJason()
	{}
	public String write2Jason(String fileIn, String res, List< Map.Entry<String, Double> > list, 
									HashMap <String, Integer> linkMat, int result) throws IOException, NumberFormatException, JSONException
	{
		File f = new File(fileIn);
		InputStream in = new FileInputStream(f);
		InputStreamReader ir = new InputStreamReader(in);
		BufferedReader br = new BufferedReader(ir);
		
		String tablejson = res.substring(0, res.lastIndexOf(File.separator));
		
		tablejson += File.separator + Main.json;
		
		File fOut = new File(res);
		OutputStream out = new FileOutputStream(fOut);
		out.close();
		out = new FileOutputStream(fOut, true);
		OutputStreamWriter or = new OutputStreamWriter(out);
		BufferedWriter bo = new BufferedWriter(or);
		File fOutjson = new File(tablejson);
		OutputStream outjson = new FileOutputStream(fOutjson);
		OutputStreamWriter orjson = new OutputStreamWriter(outjson);
		BufferedWriter bojson = new BufferedWriter(orjson);
		
		String line = "";
		int commaCount = 0;
		/*
		while( (line = br.readLine()) != null )
		{
			
			int temp = 0;
			if( ((temp = line.indexOf('}')) != -1 && line.length() > temp + 1 && line.charAt(temp + 1) != ',') 
					|| temp + 1 == line.length())
			{
				commaCount ++;
			}
			if(commaCount == 2)
			{
				break;
			}
			bo.write(line + "\n");
		}
		*/
		int ch ;
		
		while( (ch = br.read()) != -1)
		{
			
			if((char)ch == '}')
			{
				int ch2;
				if( (char)(ch2 = br.read()) != ',')
				{
					commaCount ++;
				}
				if(commaCount == 2)
					break;
				bo.write((char)ch);
				bo.write((char)ch2);
			}
			else
				bo.write((char)ch);
			
		}
		
		int countDiff = 0;
		
		for(Map.Entry<String, Double> mapping : list){
			
    		if(linkMat != null && linkMat.get(mapping.getKey()) != null)
    		{
    			continue;
    		}
    		String []key = mapping.getKey().split(",");
    		if(key[0].compareTo(key[1]) == 0)
    				continue;
    		countDiff ++;
		}
		
		if(list.size() == 0 || countDiff == 0){	//bug!!!
			bo.write("\t}\n");
			
		}
		else
			bo.write("\t},\n");
			
		int countResult = 0;
	//	JSONArray jLink = new JSONArray();
//		bojson.write("{\"total\":"+ String.valueOf(result) +",\"rows\":[\n");
		bojson.write("[\n");
		for(Map.Entry<String, Double> mapping : list){
			
    		String []key = mapping.getKey().split(",");
    		if(key[0].compareTo(key[1]) == 0)
    				continue;
    		if(linkMat != null && linkMat.get(mapping.getKey()) != null)
    		{
    			continue;
    		}
    		if(result -- > 0){
    			countResult ++;
    			/*
    			JSONObject ev_link = new JSONObject();
    			ev_link.put( "source",Integer.parseInt(key[0]));
    			ev_link.put(  "target",Integer.parseInt(key[1]));
    			ev_link.put(  "value", mapping.getValue());
    			ev_link.put( "state" ,1);
    			jLink.put(ev_link);
    			*/
    			bojson.write("{");
    			bo.write("\t{\n");
    			bo.write("\t\t\"id\":\"" + (1000000 + result) + "\",\n");
    			bo.write("\t\t\"source\":\"" + Main.itos.get(Integer.parseInt(key[0])) + "\",\n");
    			bojson.write("\"source\":\"" + Main.itos.get(Integer.parseInt(key[0])) + "\",");
    			line += Main.itos.get(Integer.parseInt(key[0])) + "\t";
    			bo.write("\t\t\"state\":1,\n");
    			bo.write("\t\t\"target\":\"" + Main.itos.get(Integer.parseInt(key[1])) + "\",\n");
    			bojson.write("\"target\":\"" + Main.itos.get(Integer.parseInt(key[1])) + "\",");
    			line += Main.itos.get(Integer.parseInt(key[1])) + "\t";
    			bo.write("\t\t\"value\":" + mapping.getValue() + ",\n");
    			bojson.write("\"value\":\"" + mapping.getValue() + "\"");
    			bo.write("\t\t\"color\":\"#ff0000\"\n");
    			line += String.valueOf(mapping.getValue()) + "\n";
    			if(result == 0 || list.size() == countResult || countDiff == countResult){
    				bo.write("\t}\n");
    				bojson.write("}\n");
    			}
    			else{
    				bojson.write("},\n");
    				bo.write("\t},\n");
    			}
    				
    			//System.out.println(key[0] + "," + key[1] +":"+mapping.getValue());
    			//System.out.println(key[0] + "," + key[1] );
    		}
    		else
    			break;
		}
		
//		bojson.write("]}");
		bojson.write("]");
		if(Main.edges == -1){
			bo.close();
			or.close();
			out.close();
			bojson.close();
			br.close();
			ir.close();
			in.close();
			Main.edges = 0;
			return "";
		}
		bo.write("\t]\n");
		bo.write("}\n");
		bo.close();
		or.close();
		out.close();
		bojson.close();
		br.close();
		ir.close();
		in.close();
		return line;
	}
}
